//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by 周先生 on 15/11/11.
//  Copyright © 2015年 周先生. All rights reserved.
//

import UIKit
import AFNetworking
//viewModel将一些业务逻辑封装到这个类里面 让这个隔离的更加好
class UserAccountViewModel: NSObject {

    //增加userAccount属性
    var account: UserAccount?
    //用户是否登录的属性
    var userLogin: Bool {
    
    return account?.access_token != nil
    }
    //用户姓名
    var userName: String? {
    
        return account?.name
    }
    //用户头像地址
    var headUrl: NSURL? {
    
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    //用户access_token
    var token: String? {
    
        return account?.access_token
    }
    
    

    //在init方法中获取用户账户
    override init() {
        account = UserAccount.loadAccount()
    }
    
    //加载用户token
     func loadAccessToken(code: String, finished: (error: NSError?) -> ()) {
        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
        let urlString = "oauth2/access_token"

        let parameters = ["client_id": client_id,"client_secret":client_secret,"grant_type" : "authorization_code","code":code,"redirect_uri":redirect_uri]
        
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            if let dict = result as? [String: AnyObject] {
                //                let access_token = dict["access_token"] as? String
                //开始字典转模型
                let account = UserAccount(dict: dict)
                self.loadUserInfo(account, finished: finished)
                //                print(account)
                //                let uid = dict["uid"] as? String
                //                //相信后端给的数据一定能取到相应的值
                //                print(dict)
                //                self.loadUserInfo(access_token!, uid: uid!)
            }
            }) { (_, error) -> Void in
                print(error)
        }
        
    }
    //加载用户信息
    private func loadUserInfo(account:UserAccount, finished: (error: NSError?) -> ()) {
//        let urlString = "https://api.weibo.com/2/users/show.json"
        let urlString = "2/users/show.json"

        let parameters = ["access_token": account.access_token!, "uid": account.uid!]
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            if let dict = result as? [String: AnyObject] {
                account.avatar_large = dict["avatar_large"] as? String
                account.name = dict["name"] as? String
                
                account.saveAccount()
                //执行闭包
                finished(error: nil)
            }
            
            }) { (_, error) -> Void in
                print(error)
        }
        
    }

}
